package struct;

import com.alibaba.fastjson.JSONObject;
import struct.enums.ResourceType;

import java.util.List;

public class ResourceConfig {
    public final static String NAME_FIELD = "name";
    private final static String TYPE_FIELD = "type";
    private final static String FIELDS_FIELD = "fields";

    public String name;
    public ResourceType type;
    public List<String> fields;
    JSONObject jo;

    public ResourceConfig(String name, ResourceType type, List<String> fields) {
        this.name = name;
        this.type = type;
        this.fields = fields;
    }

    public static ResourceConfig fromString(String json) {
        JSONObject jo = JSONObject.parseObject(json);
        return fromJSONObject(jo);
    }

    public static ResourceConfig fromJSONObject(JSONObject jo) {
        String name = jo.getString(NAME_FIELD);
        ResourceType type = ResourceType.fromString(jo.getString(TYPE_FIELD));
        List<String> fields = null;
        if (jo.getJSONArray(FIELDS_FIELD) != null) {
            fields = jo.getJSONArray(FIELDS_FIELD).toJavaList(String.class);
        }
        ResourceConfig resourceConfig = new ResourceConfig(name, type, fields);
        resourceConfig.jo = jo;
        return resourceConfig;
    }

    @Override
    public String toString() {
        if (jo == null) {
            jo = new JSONObject();
            jo.put(NAME_FIELD, name);
            jo.put(TYPE_FIELD, type.toString());
            jo.put(FIELDS_FIELD, fields);
        }
        return jo.toJSONString();
    }
}
